<template>
<view>
<view class="container">
  <view class="selectList">
    <view class="selectItem" @click.stop="tolinkUrl" data-link="select_location.html">
      <view class="selectItemLeft">
        <image class="selectItemLeftIcon" src="https://image1.sansancloud.com/xianhua/2019_5/8/11/4/11_202.jpg?x-oss-process=style/preview_120"></image>
        <text class="selectItemText">选择小区/写字楼等</text>
      </view>
      <image class="selectItemRightIcon" src="https://image1.sansancloud.com/xianhua/2019_4/3/18/3/24_160.jpg?x-oss-process=style/preview_120"></image>
    </view>
    <view class="selectItem" @click.stop="getLocationAddress">
      <view class="selectItemLeft">
        <image class="selectItemLeftIcon" src="https://image1.sansancloud.com/xianhua/2019_5/8/11/4/11_200.jpg?x-oss-process=style/preview_120"></image>
        <text class="selectItemText">点击定位当前地点</text>
      </view>
      <image class="selectItemRightIcon" src="https://image1.sansancloud.com/xianhua/2019_4/3/18/3/24_160.jpg?x-oss-process=style/preview_120"></image>
    </view>
  </view>
  <view class="addrtop"><text>我的收货地址</text></view>
  <view class="addrItems" v-for="(addr, index) in addrData" :key="index" @click.stop="selectAddressFun(addr)">
    <view class="addrItems_left">
      <image class="addr_icon" mode="aspectFit" src="https://image1.sansancloud.com/xianhua/2019_12/12/13/49/30_402.jpg?x-oss-process=style/preview_120"></image>
      <view class="addrItems_info">
        <text style="font-size:30rpx;font-weight: bold" v-if="addr.community">{{addr.community}}</text>
        <text style="font-size:30rpx;font-weight: bold" v-else>{{addr.province}} {{addr.city}} {{addr.area}} {{addr.address}}</text>
        <text class="font2" v-if="addr.community">{{addr.address}}</text>
        <text class="font2">{{addr.contactName}} {{addr.telNo}}</text>
      </view>
    </view>
    <image :data-id="addr.id" @click.stop="writeAddr" class="edit_icon" mode="aspectFit" src="https://image1.sansancloud.com/xianhua/2019_4/25/16/12/2_533.jpg?x-oss-process=style/preview_120"></image>
  </view>
</view>
<view class="addnewAddr" @click.stop="tolinkUrl" data-link="add_address.html" :style="'background:' + setting.platformSetting.defaultColor">
  <image src="https://image1.sansancloud.com/xianhua/2019_12/12/14/58/40_162.jpg?x-oss-process=style/preview_120"></image>
  <view>新增地址</view>
</view>
</view>
</template>

<script>

export default {
  data() {
    return {
      setting: null,
      loginUser: null,
      addrData: null,
      selectAddressData: {},
      selectAddress:{},
      reqLocation: false
    };
  },

  components: {},
  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      setting: getApp().globalData.setting
    });
    this.setData({
      loginUser: getApp().globalData.loginUser
    });
    this.getAddr();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    that.getAddr();
    that.returnSelectAddressFun();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getAddr();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},
  methods: {
    returnSelectAddressFun:function(){
        let that=this;
        console.log("===returnSelectAddressFun===",that.reqLocation)
        if (that.reqLocation) {
          let locationList = {};
          var pages = getCurrentPages();
          var currPage = pages[pages.length - 1]; //当前页面
        
          console.log(currPage); //就可以看到data里mydata的值了
          let itemData=currPage.$vm.data?currPage.$vm.data.selectAddress:currPage.$vm._data.selectAddress;
          console.log("从选择地点页面返回", that.selectAddress);
          that.selectAddress=itemData
          if (itemData) {
            console.log("选择了地点");
            that.selectAddress=itemData
            that.selectAddressFun(that.selectAddress);
          } else {
            console.log("没选择地点");
          }
        }
    },
    getLocationAddress: function () {
      //获取当前地址
      let that = this;
      wx.getLocation({
        type: 'gcj02',
        success: function (res) {
          console.log("=====getLocationAddress====", res);
          let latitude = res.latitude;
          let longitude = res.longitude;
          console.log(longitude + "..............." + latitude); // 获取附近店铺数据

          let pageParam = {
            "longitude": longitude,
            "latitude": latitude
          };
          console.log(pageParam);
          that.getLoctionAddr(pageParam);
        }
      });
    },
    getLoctionAddr: function (pageParam) {
      //根据当前经纬度获取当前详细地址
      var that = this;
      var param = {};
      param.longitude = pageParam.longitude;
      param.latitude = pageParam.latitude;
      param['type'] = 1;
      var customIndex = getApp().globalData.AddClientUrl("/get_location_detail.html", param, 'get');
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log("=====getLoctionAddr====", res.data);
          let data = res.data.result;
          let params = {
            longitude: pageParam.longitude,
            latitude: pageParam.latitude,
            province: data.addressComponent ? data.addressComponent.province : data.address_component.province,
            city: data.addressComponent ? data.addressComponent.city : data.address_component.city,
            street: data.addressComponent ? data.addressComponent.street : data.address_component.street,
            value: data.pois ? data.pois[0].title : data.formatted_addresses.recommend // value: data.formatted_address || data.formatted_addresses.recommend,

          };
          console.log("====params=====", params);
          that.setLoctionAddr(params);
          that.setData({
            selectAddressData: params
          });
          that.getNearMenDian(params);
          wx.hideLoading();
        },
        fail: function (res) {
          wx.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },
    selectAddressFun: function (info) {
      //选择已存在的用户地址
      console.log("======selectAddressFun=======", info);
      let that = this;
      let addressInfo=info;
      let address = {
        longitude: addressInfo.longitude,
        latitude: addressInfo.latitude,
        province: addressInfo.province || '',
        city: addressInfo.city || '',
        street: addressInfo.area || '',
        detailedAddress: addressInfo.address || '',
        community: addressInfo.community,
        value: addressInfo.community || addressInfo.address
      };
      addressInfo = address;
      that.setData({
        selectAddressData: addressInfo
      });
      that.getNearMenDian(addressInfo);
      let params = {
        longitude: addressInfo.longitude,
        latitude: addressInfo.latitude
      };

      if (addressInfo.province) {
        params = Object.assign({}, params, {
          province: addressInfo.province,
          city: addressInfo.city,
          street: addressInfo.street || addressInfo.area
        });
      }

      console.log("====params=====", params);
      that.setLoctionAddr(params);
    },
    setLoctionAddr: function (pageParam) {
      //设置地址
      let that = this;
      let customIndex = getApp().globalData.AddClientUrl("/setLocation.html", pageParam, 'get');
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log("=====setLoctionAddr====", res.data);
          wx.hideLoading();
        },
        fail: function (res) {
          wx.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },
    //  附近门店取第一个
    getNearMenDian: function (addressInfo) {
      let that = this;
      let latitude = addressInfo.latitude;
      let longitude = addressInfo.longitude;
      let menDian = {
        longitude: longitude,
        latitude: latitude
      };
      let menDianYangShi = getApp().globalData.AddClientUrl("/find_mendians.html", menDian, 'get');
      wx.request({
        url: menDianYangShi.url,
        data: menDianYangShi.params,
        header: getApp().globalData.headerPost,
        method: 'GET',
        success: function (res) {
          console.log("===附近门店取第一个", res.data);

          if (res.data.errcode == "-1") {
            wx.showToast({
              title: res.data.errMessage,
              image: '/wxcomponents/images/icons/tip.png',
              duration: 2000
            });
          } else {
            let firstMendian = res.data.relateObj.result;

            if (firstMendian.length != 0 && firstMendian[0].id) {
              // 当数据都存在，然后就开始设置门店
              that.setUpMenDian(firstMendian[0].id);
            } else {
              wx.showToast({
                title: "您附近没有相关门店哦!",
                image: '/wxcomponents/images/icons/tip.png',
                duration: 2000
              });
            }
          }
        }
      });
    },
    // 设置门店（当门店信息都有的时候，将门店id传到服务器。）
    setUpMenDian: function (menDianID) {
      let that = this;
      let id = menDianID;
      let menDianParameter = {
        mendianId: id
      };
      let menDianYangShi = getApp().globalData.AddClientUrl("/location_mendian.html", menDianParameter, 'get');
      wx.request({
        url: menDianYangShi.url,
        data: menDianYangShi.params,
        header: getApp().globalData.headerPost,
        method: 'GET',
        success: function (res) {
          console.log('=====setUpMenDian====', res);

          if (res.data.errcode == "-1") {
            wx.showToast({
              title: res.data.errMessage,
              image: '/wxcomponents/images/icons/tip.png',
              duration: 2000
            });
          } else {
            console.log("设置成功", that.selectAddressData);
            wx.setStorageSync('selectAddressData', that.selectAddressData);
            let pages = getCurrentPages(); //当前页面

            let prevPage = pages[pages.length - 2]; //上一页面

            console.log("====prevPage===", prevPage);

            if (prevPage) {
              try{
                  prevPage.onPullDownRefresh();
              }catch(e){
                  prevPage.refreshPage();
              }
            }

            wx.navigateBack({
              delta: 1
            });
          }
        }
      });
    },

    /* 编辑 */
    writeAddr: function (e) {
      var addrId = e.currentTarget.dataset.id;

      for (let i = 0; i < this.addrData.length; i++) {
        if (addrId == this.addrData[i].id) {
          getApp().globalData.EditAddr = this.addrData[i];
        }
      }

      wx.navigateTo({
        url: '../add_address/index?addrId=' + addrId
      });
    },
    tolinkUrl: function (e) {
      if (!getApp().globalData.loginUser) {
        wx.showModal({
          title: '提示',
          content: '主人~您还在登陆哦!稍等片刻',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
            } else if (res.cancel) {
              console.log('用户点击取消');
            }
          }
        });
        return;
      }

      let that = this;
      let linkUrl = e.currentTarget.dataset.link;

      if (linkUrl.indexOf("select_location.html") != -1) {
        console.log("选择位置");
        that.setData({
          reqLocation: true
        });
      } else {
        that.setData({
          reqLocation: false
        });
      }

      getApp().globalData.linkEvent(linkUrl);
    },
    getAddr: function () {
      if (!getApp().globalData.checkIfLogin()) {
        return;
      }

      var customIndex = getApp().globalData.AddClientUrl("/get_login_user_address_list.html");
      var that = this; // wx.showLoading({
      //   title: 'loading'
      // })

      getApp().globalData.showToastLoading('loading', true); //拿custom_page 

      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log('-------地址---------');
          console.log(res.data);

          if (res.data.result.errcode == '-1') {
            console.log('err');
            getApp().globalData.echoErr(res.data.result.errMsg);
          } else {
            that.setData({
              addrData: res.data.result
            });
          }

          wx.hideLoading();
        },
        fail: function (res) {
          wx.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style scoped>
@import "./index.css";
</style>